package com.vogue.supplymall.admin.business.controller;

import com.vogue.supplymall.account.domain.model.AdminUser;
import com.vogue.supplymall.admin.business.common.AdminMemUtils;
import com.vogue.supplymall.admin.business.common.OpenOrganCheckUtils;
import com.vogue.supplymall.admin.business.common.constant.ErrorCode;
import com.vogue.supplymall.admin.business.domain.biz.AdminPrivatePlatformBiz;
import com.vogue.supplymall.admin.business.exception.AdminProcessException;
import com.vogue.supplymall.common.domain.dto.ControllerResultInfo;
import com.vogue.supplymall.common.domain.dto.admin.PrivatePlatformAppInfo;
import com.vogue.supplymall.common.domain.dto.admin.PrivatePlatformInfo;
import com.vogue.supplymall.common.exception.ParamErrorException;
import com.vogue.supplymall.common.exception.ParamIsExistException;
import com.vogue.supplymall.common.exception.UploadException;
import org.apache.commons.lang3.StringUtils;
import org.apache.shiro.SecurityUtils;
import org.slf4j.Logger;
import org.slf4j.LoggerFactory;
import org.springframework.http.HttpStatus;
import org.springframework.http.ResponseEntity;
import org.springframework.validation.annotation.Validated;
import org.springframework.web.bind.annotation.PathVariable;
import org.springframework.web.bind.annotation.RequestBody;
import org.springframework.web.bind.annotation.RequestMapping;
import org.springframework.web.bind.annotation.RequestMethod;
import org.springframework.web.bind.annotation.RequestParam;
import org.springframework.web.bind.annotation.RestController;
import org.springframework.web.multipart.commons.CommonsMultipartFile;

import javax.annotation.Resource;
import java.util.Map;

/**
 * The type Admin private platform controller.
 * 管理私有化平台的controller
 *
 * @author zhangliang
 * @date Create in 2018-07-09
 */
@RestController
public class AdminPrivatePlatformController extends BaseController {
    /**
     * The constant log.
     */
    public static final Logger LOGGER_ADMINPRIVATEPLATFORMCONTROLLER = LoggerFactory.getLogger(AdminPrivatePlatformController.class);
    @Resource
    private AdminPrivatePlatformBiz adminPrivatePlatformBiz;
    @Resource
    private AdminMemUtils adminMemUtils;

    /**
     * Gets private platform info.
     * 获取所有的私有化平台信息
     *
     * @param appver              the appver
     * @param privatePlatformInfo the private platform info
     * @return the private platform info
     */
    @RequestMapping(value = "/is/{appver}/admin/business/private/platform/list", method = RequestMethod.POST)
    public ResponseEntity<Object> getPrivatePlatformInfo(@PathVariable("appver") String appver,
                                                         @RequestBody PrivatePlatformInfo privatePlatformInfo) {
        LOGGER_ADMINPRIVATEPLATFORMCONTROLLER.info("get private platform list start >>>>>> ");
        ControllerResultInfo resultInfo = new ControllerResultInfo();
        resultInfo.setResult(true);
        resultInfo.setData(adminPrivatePlatformBiz.findAllPrivatePlatform(privatePlatformInfo));
        LOGGER_ADMINPRIVATEPLATFORMCONTROLLER.info(" <<<<<< get private platform list end");
        return new ResponseEntity<>(resultInfo, HttpStatus.OK);
    }

    /**
     * Add private platfrom response entity.
     * 添加一个私有化平台信息
     *
     * @param appver              the appver
     * @param privatePlatformInfo the private platform info
     * @return the response entity
     */
    @RequestMapping(value = "/is/{appver}/admin/business/private/platform/add", method = RequestMethod.POST)
    public ResponseEntity<Object> addPrivatePlatfrom(@PathVariable("appver") String appver,
                                                     @RequestBody @Validated PrivatePlatformInfo privatePlatformInfo) {
        LOGGER_ADMINPRIVATEPLATFORMCONTROLLER.info("add private platform start >>>>>> ");
        AdminUser info = new AdminUser();
        if (SecurityUtils.getSubject().isAuthenticated()) {
            info = (AdminUser) SecurityUtils.getSubject().getPrincipal();
            OpenOrganCheckUtils.checkAddPrivate(privatePlatformInfo);
            LOGGER_ADMINPRIVATEPLATFORMCONTROLLER.info("获取登信息：" + info.getLoginname());
        } else {
            LOGGER_ADMINPRIVATEPLATFORMCONTROLLER.info("获取登信息失败！");
        }

        ControllerResultInfo resultInfo = new ControllerResultInfo();
        try {
            Long id = adminPrivatePlatformBiz.addPrivatePlatform(privatePlatformInfo, info);
            resultInfo.setData(id);
            adminMemUtils.setPlatform();
        } catch (ParamIsExistException pe) {
            throw new ParamIsExistException(pe.getArgs());
        } catch (RuntimeException re) {
            throw new AdminProcessException(ErrorCode.ProcessFail.getCode(), ErrorCode.ProcessFail.getMsg());
        }
        resultInfo.setResult(true);

        LOGGER_ADMINPRIVATEPLATFORMCONTROLLER.info(" <<<<<< add private platform end");
        return new ResponseEntity<>(resultInfo, HttpStatus.OK);
    }


    /**
     * Update private platfrom response entity.
     * 更新一个私有化平台信息
     *
     * @param appver              the appver
     * @param privatePlatformInfo the private platform info
     * @return the response entity
     */
    @RequestMapping(value = "/is/{appver}/admin/business/private/platform/update", method = RequestMethod.POST)
    public ResponseEntity<Object> updatePrivatePlatfrom(@PathVariable("appver") String appver, @RequestBody PrivatePlatformInfo privatePlatformInfo) {
        LOGGER_ADMINPRIVATEPLATFORMCONTROLLER.info("update private platform start >>>>>> ");
        AdminUser info = new AdminUser();
        if (SecurityUtils.getSubject().isAuthenticated()) {
            info = (AdminUser) SecurityUtils.getSubject().getPrincipal();
            if (null == privatePlatformInfo.getId()
                    || null == privatePlatformInfo.getAppInfo()
                    || 0 == privatePlatformInfo.getAppInfo().size()
                    || null == privatePlatformInfo.getName()
                    || null == privatePlatformInfo.getPaytogether()
                    || null == privatePlatformInfo.getEntrymode()) {
                throw new ParamErrorException("");
            }
            OpenOrganCheckUtils.checkAddPrivate(privatePlatformInfo);
            LOGGER_ADMINPRIVATEPLATFORMCONTROLLER.info("获取登信息：" + info.getLoginname());
        } else {
            LOGGER_ADMINPRIVATEPLATFORMCONTROLLER.info("获取登信息失败！");
        }

        ControllerResultInfo resultInfo = new ControllerResultInfo();
        try {
            adminPrivatePlatformBiz.updatePrivatePlatform(privatePlatformInfo, info);
            resultInfo.setData(null);
            adminMemUtils.setPlatform();
        } catch (ParamErrorException re) {
            throw new ParamErrorException("");
        } catch (RuntimeException re) {
            throw new AdminProcessException(ErrorCode.ProcessFail.getCode(), ErrorCode.ProcessFail.getMsg());
        }
        resultInfo.setResult(true);

        LOGGER_ADMINPRIVATEPLATFORMCONTROLLER.info(" <<<<<< update private platform end");
        return new ResponseEntity<>(resultInfo, HttpStatus.OK);
    }

    /**
     * Upload app response entity.
     * 上传app到青云服务器
     *
     * @param appver    the appver
     * @param extension the extension
     * @param type      the type
     * @param name      the name
     * @param file      the file
     * @return the response entity
     */
    @RequestMapping(value = "/is/{appver}/admin/business/private/platform/uploadapp", method = RequestMethod.POST)
    public ResponseEntity<Object> uploadApp(@PathVariable("appver") String appver,
                                            @RequestParam("extension") String extension,
                                            @RequestParam("type") String type,
                                            @RequestParam("name") String name,
                                            @RequestParam("iosService") String iosService,
                                            @RequestParam("file") CommonsMultipartFile file) {
        LOGGER_ADMINPRIVATEPLATFORMCONTROLLER.info("upload app start >>>>>> ");
        if (file.isEmpty()) {
            throw new ParamErrorException("请选择上传文件");
        }
        PrivatePlatformAppInfo appInfo = new PrivatePlatformAppInfo();
        appInfo.setFile(file);
        appInfo.setName(name);
        appInfo.setIosService(iosService);
        appInfo.setType(Integer.valueOf(type));
        appInfo.setFilename(name);
        appInfo.setExtension(extension);
        ControllerResultInfo resultInfo = new ControllerResultInfo();
        try {
            Map<String, String> data = adminPrivatePlatformBiz.uploadApp(appInfo);
            resultInfo.setData(data);
        } catch (UploadException e) {
            throw new UploadException(e.getArgs());
        } catch (Exception e) {
            throw new UploadException("");
        }
        resultInfo.setResult(true);
        resultInfo.setMsg("上传成功");
        LOGGER_ADMINPRIVATEPLATFORMCONTROLLER.info(" <<<<<< upload app end");
        return new ResponseEntity<>(resultInfo, HttpStatus.OK);
    }

    /**
     * Add app info response entity.
     * 保存app信息
     *
     * @param appver  the appver
     * @param appInfo the app info
     * @return the response entity
     */
    @RequestMapping(value = "/is/{appver}/admin/business/private/platform/app/add", method = RequestMethod.POST)
    public ResponseEntity<Object> addAppInfo(@PathVariable("appver") String appver, @RequestBody PrivatePlatformAppInfo appInfo) {
        LOGGER_ADMINPRIVATEPLATFORMCONTROLLER.info("add private platfomr app info start >>>>>> ");
        AdminUser info = new AdminUser();
        if (SecurityUtils.getSubject().isAuthenticated()) {
            info = (AdminUser) SecurityUtils.getSubject().getPrincipal();
            if (null == appInfo.getAppid()
                    || null == appInfo.getType()
                    || null == appInfo.getOnlineurl()
                    || null == appInfo.getQrcodeurl()) {
                throw new ParamErrorException("");
            }
            LOGGER_ADMINPRIVATEPLATFORMCONTROLLER.info("获取登信息：" + info.getLoginname());
        } else {
            LOGGER_ADMINPRIVATEPLATFORMCONTROLLER.info("获取登信息失败！");
        }

        try {
            adminPrivatePlatformBiz.saveAppInfo(appInfo, info);
        } catch (ParamErrorException re) {
            throw new ParamErrorException("");
        } catch (RuntimeException re) {
            throw new AdminProcessException(ErrorCode.ProcessFail.getCode(), ErrorCode.ProcessFail.getMsg());
        }

        ControllerResultInfo resultInfo = new ControllerResultInfo();
        resultInfo.setResult(true);
        resultInfo.setData(null);
        resultInfo.setMsg("保存成功");
        LOGGER_ADMINPRIVATEPLATFORMCONTROLLER.info(" <<<<<< add private platfomr app info end");
        return new ResponseEntity<>(resultInfo, HttpStatus.OK);
    }

    /**
     * Gets download page.
     * 获取某一平台下载页
     *
     * @param appver the appver
     * @param name   the name
     * @return the download page
     */
    @RequestMapping(value = "/ns/{appver}/admin/business/private/platform/download/{name}", method = RequestMethod.POST)
    public ResponseEntity<Object> getDownloadPage(@PathVariable("appver") String appver, @PathVariable String name) {
        LOGGER_ADMINPRIVATEPLATFORMCONTROLLER.info("get download page start >>>>>> ");
        ControllerResultInfo resultInfo = new ControllerResultInfo();
        if (StringUtils.isEmpty(name)) {
            resultInfo.setResult(true);
            resultInfo.setMsg("没有获取到平台");
        } else {
            resultInfo.setData(adminPrivatePlatformBiz.getDownloadPage(name));
        }
        LOGGER_ADMINPRIVATEPLATFORMCONTROLLER.info(" <<<<<< get download page end");
        return new ResponseEntity<>(resultInfo, HttpStatus.OK);
    }
}
